﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LogfileEditor
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 开始按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            string filePath = txtPath.Text;
            string keywordExpression = txtRule.Text;
            if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(keywordExpression))
            {
                MessageBox.Show("请选择文件和规则！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!File.Exists(filePath))
            {
                MessageBox.Show("文件不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            SaveOrUpdateAppSetting("LastRule", txtRule.Text);
            DisabledBtn();
            backgroundWorker1.RunWorkerAsync();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            txtRule.Text = ConfigurationManager.AppSettings["LastRule"];
            backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
        }

        /// <summary>
        /// 后台任务完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            EnabledBtn();
        }

        /// <summary>
        /// 打开文件按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtPath.Text = openFileDialog1.FileName;
                SaveOrUpdateAppSetting("LastFilePath", txtPath.Text);
            }
        }
        /// <summary>
        ///  后台任务事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var removed = EditFile(txtPath.Text, txtRule.Text);
                MessageBox.Show($"文件已修改！ {removed} 行被删除。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                EnabledBtn();
            }
        }

        /// <summary>
        /// 停用按钮并显示loading
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisabledBtn()
        {
            btnStart.Enabled = false;
            btnStart.Text = "请稍后...";
        }
        private void EnabledBtn()
        {
            btnStart.Enabled = true;
            btnStart.Text = "开始";
        }

        /// <summary>
        /// 编辑文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="keywordExpression"></param>
        public static int EditFile(string filePath, string keywordExpression)
        {
            int removed = 0;
            //string tempFilePath = Path.GetTempFileName();
            string tempFilePath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_new" + Path.GetExtension(filePath);
            using (StreamReader reader = new StreamReader(filePath))
            using (StreamWriter writer = new StreamWriter(tempFilePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    //需求变了,要保留匹配到的行
                    if (EditorCore.ShouldKeepLine(line, keywordExpression))
                    {
                        writer.WriteLine(line);
                    }
                    else
                    {
                        removed++;
                    }
                }
            }

            //File.Move(tempFilePath, filePath);

            return removed;
        }

        /// <summary>
        /// 判断是否应该移除该行
        /// </summary>
        /// <param name="line"></param>
        /// <param name="keywordExpression"></param>
        /// <returns></returns>


        /// <summary>
        /// 保存或更新AppSettings中的键值对
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SaveOrUpdateAppSetting(string key, string value)
        {
            // 打开App.Config文件
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 检查AppSetting中是否已存在该键
            if (config.AppSettings.Settings[key] != null)
            {
                // 更新现有的键值
                config.AppSettings.Settings[key].Value = value;
            }
            else
            {
                // 添加新的键值
                config.AppSettings.Settings.Add(key, value);
            }

            // 保存更改
            config.Save(ConfigurationSaveMode.Modified);

            // 强制重新加载配置文件的AppSettings部分
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (EditorCore.ShouldKeepLine(txtContentTest.Text, txtRuleTest.Text))
            {
                MessageBox.Show("匹配成功！该行会被保留！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("匹配失败，该行不会被保留！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}
